from django.core.management.base import BaseCommand
from django.utils.text import slugify
from core.models import Category
import os

class Command(BaseCommand):
    help = '从目录结构导入菜单到数据库'

    def add_arguments(self, parser):
        parser.add_argument('directory', type=str, help='要导入的目录路径')

    def handle(self, *args, **options):
        directory = options['directory']
        self.import_directory(directory)

    def clean_name(self, name):
        # 移除序号前缀（如 "01_"）
        if '_' in name:
            parts = name.split('_', 1)
            if parts[0].isdigit():
                return parts[1]
        return name

    def get_description_from_readme(self, directory):
        readme_path = os.path.join(directory, 'README.md')
        if os.path.exists(readme_path):
            try:
                with open(readme_path, 'r', encoding='utf-8') as f:
                    first_line = f.readline().strip()
                    if first_line.startswith('#'):
                        return first_line.lstrip('#').strip()
                    return first_line
            except Exception as e:
                self.stdout.write(self.style.WARNING(f'读取README失败: {str(e)}'))
        return ''

    def get_description_from_file(self, file_path):
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                first_line = f.readline().strip()
                if first_line.startswith('#'):
                    return first_line.lstrip('#').strip()
                return first_line
        except Exception as e:
            self.stdout.write(self.style.WARNING(f'读取文件失败: {str(e)}'))
        return ''

    def import_directory(self, start_path, parent=None, order=0):
        # 获取目录名
        dir_name = os.path.basename(start_path)
        if dir_name == 'books':  # 跳过顶级目录
            base_order = 0
            for item in sorted(os.listdir(start_path)):
                item_path = os.path.join(start_path, item)
                if os.path.isdir(item_path):
                    self.import_directory(item_path, None, base_order)
                    base_order += 1
            return

        # 清理目录名
        clean_dir_name = self.clean_name(dir_name)
        
        # 获取目录描述
        description = self.get_description_from_readme(start_path)
        
        # 创建或更新分类
        category_slug = slugify(clean_dir_name, allow_unicode=True)
        category, created = Category.objects.update_or_create(
            slug=category_slug,
            defaults={
                'title': clean_dir_name,
                'parent': parent,
                'order_index': order,
                'description': description or clean_dir_name
            }
        )

        if created:
            self.stdout.write(self.style.SUCCESS(f'创建分类: {clean_dir_name}'))
        else:
            self.stdout.write(self.style.SUCCESS(f'更新分类: {clean_dir_name}'))

        # 处理子目录和文件
        base_order = 0
        
        # 首先处理子目录
        for item in sorted(os.listdir(start_path)):
            item_path = os.path.join(start_path, item)
            if os.path.isdir(item_path) and not item.startswith('.'):
                self.import_directory(item_path, category, base_order)
                base_order += 1

        # 然后处理文档文件
        for item in sorted(os.listdir(start_path)):
            if item.endswith('.md') and item != 'README.md':
                item_path = os.path.join(start_path, item)
                doc_name = self.clean_name(item[:-3])  # 移除 .md 后缀
                doc_description = self.get_description_from_file(item_path)
                
                doc_slug = slugify(doc_name, allow_unicode=True)
                doc, created = Category.objects.update_or_create(
                    slug=doc_slug,
                    defaults={
                        'title': doc_name,
                        'parent': category,
                        'order_index': base_order,
                        'description': doc_description or doc_name,
                        'is_document': True,
                        'document_path': os.path.relpath(item_path, start_path)
                    }
                )

                if created:
                    self.stdout.write(self.style.SUCCESS(f'创建文档: {doc_name}'))
                else:
                    self.stdout.write(self.style.SUCCESS(f'更新文档: {doc_name}'))
                
                base_order += 1 